//
//  PopTransitionAnimation.m
//  29-TransitionHomework
//
//  Created by 曹曹 on 16/8/23.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "PopTransitionAnimation.h"
#import "ViewController.h"
#import "MyTableViewCell.h"
#import "DetailViewController.h"

@implementation PopTransitionAnimation
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.5f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    ViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    DetailViewController *fromeVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    [containerView addSubview:toVC.view];
    MyTableViewCell *cell = [toVC.tableView cellForRowAtIndexPath:toVC.indexPath];
    cell.cellImageView.hidden = YES;
    
    UIView *snapView = [fromeVC.detailImageView snapshotViewAfterScreenUpdates:NO];
    snapView.frame = fromeVC.detailImageView.frame;
    [containerView addSubview:snapView];
    
    toVC.view.alpha = 0;
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        CGRect newRect = [toVC.view convertRect:cell.contentView.frame fromView:cell];
        snapView.frame = newRect;
        toVC.view.alpha = 1;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
        cell.cellImageView.hidden = NO;
        [snapView removeFromSuperview];
    }];
}

@end
